import {
	toNumber
} from "../utils/transform";
import {
	empty
} from "../utils/validate";
export const localPostage = {
	data() {
		return {
			current_address_can_buy: true, 
		}
	},
	methods: {
		$setAreaCanBuy(value = false) {
			this.current_address_can_buy = value
		},

		$getPostage(num, quantity, postage, freightTemplate, price) {
			this.$setAreaCanBuy(true)
			num = toNumber(num)
			quantity = toNumber(quantity)
			postage = toNumber(postage)
			if (!freightTemplate || !freightTemplate[0]) { 
				return this.$defaultPostageModule(num, quantity, postage)
			} else {
				return this.$getPostageBySelfModule(num, freightTemplate, num * price)
			}
		},

		$defaultPostageModule(num, quantity, postage) {
			if (num >= quantity) postage = 0
			
			return {
				price:postage,
				msg:''
			}
		},

		$getPostageBySelfModule(buyNum, postageModule, prodPrice) {
			let address = this.$getUserSelectAddress()
			if (!address) { 
				this.$setAreaCanBuy()
				return {
					price:0,
					msg:'未选择地址'
				}
			} else {
				let moduleIndex = postageModule.findIndex(item => {
					return item.area.split('-').some(city => address.includes(city))
				})
				if (moduleIndex > -1) {
					return {
						price:this.$postageModuleOne(buyNum, postageModule[moduleIndex], prodPrice),
						msg:''
					}
				} else {
					this.$setAreaCanBuy()
					return {
						price:0,
						msg:'不在配送范围内'
					}
				}
			}
		},
		$postageModuleOne(buyNum, moduleItem, prodPrice) {
			let minAmount = toNumber(moduleItem.min_amount) 
			let freight = toNumber(moduleItem.freight) 
			let num = toNumber(moduleItem.num) 
			let renew = toNumber(moduleItem.renew) 
			let postage = freight 
			if (moduleItem.type == 1 && prodPrice >= minAmount) { 
				postage = 0
			}else if(moduleItem.type == 2 && buyNum >= minAmount){
				postage = 0
			} else if (num > 0 && buyNum > num) { 
				postage += (buyNum - num) * renew
			}
			return postage
		},

		$checkCanBuyFromPostageModule() {
			if (this.current_address_can_buy) {
				return true
			} else {
				this.$toast('当前地址不在配送区域')
				return false
			}
		},

		$getUserSelectAddress() {
			let address = ''
			try {
				address = this.vuex_address ? this.vuex_address.address : ''
				return address
			} catch (e) {
				return address
			}
		}
	}
}
